<template>
  <div :class="!isDialog?'clear-wrap':'clearfix'">
    <div class="zhezhao" :class="checkSingleLabel?'show-zhezhao':'hide-zhezhao'" v-show="flag === 'QC'"></div>
    <div class="box-wrap" :class="flag === 'QC'?'QC-label-select':''">
      <span class="label-title" v-show="!isDialog">{{$t('public.callLabel')}}：</span>
      <div class="label-contain" :class="isDialog?'phoneBar-padding':''" v-if="callLabel.length <=0">{{$t('call.noCallLabel')}}</div>
      <div class="label-contain" :class="isDialog?'phoneBar-padding':''" v-else>
        <ul class="ul-name clearfix" v-show="!loading">
          <!--是多级标签并且不是停用的-->
          <li v-for ='(item,index) in checkCallLabel' :key="index" v-if="item.indexOf('@') > -1 && trunLableNameById(item)" :title="trunLableNameById(item)" class="label-cursor">{{trunLableNameById(item)}}</li>
        </ul>
        <div :class="hasMulti?'has-multi':''">
          <div v-for="(item, index) in preCheckLabel" :key="index" class="label-clear">
            <label class="label-box">
              <input type="checkbox" class="label-cursor" v-model.trim="item.checked" :disabled="disabled" :name="item._id" :value="item._id" :title="item.name" @change="changeCallLabel(item._id,item.name,item.checked)"><span class="label-text">{{item.name}}</span>
            </label>
          </div>
        </div>
      </div>
    </div>
    <!--<el-button v-show="!phoneBarFlag && getTabType === 'cdr_my' || getTabType === 'cdr_all'&&!phoneBarFlag || !phoneBarFlag && getTabType === 'cdr_pending'" :class="getTabType === 'cdr_all'?'opera-left': ''" class="fr primary_btn rest-btn" size="small" @click.stop="checkOperationLog">{{$t('call.checkOperate')}}</el-button>-->
    <el-button v-show="showOperaLog" :class="getTabType === 'cdr_all'?'opera-left': ''" class="fr primary_btn rest-btn" size="small" @click.stop="checkOperationLog">{{$t('call.checkOperate')}}</el-button>
    <el-dialog :title="$t('public.changeLog')" :visible.sync="checkOpearaDialog" class='call-label-dialog'>
      <div v-if="operaHistory&&operaHistory.length<=0" class="no-opera">{{$t('call.noOperate')}}</div>
      <operation-log v-else :labelOperaHistory = 'operaHistory'></operation-log>
    </el-dialog>
    <el-dialog :title="$t('public.tip')" append-to-body modal-append-to-body :visible.sync="checkSingleLabel" :modal="flag==='QC'?false:true" :show-close="false">
      <span>{{$t('call.replaceMultiLabel')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button  class="primary_btn" @click="cancleWarning">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click="warningCheckLabel">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  // 此组件是单标签组件，此组件还涉及有多级标签旧数据替换成单标签的情况
  // *****标签现状： kf只有多级标签配置 cc是单标签和多级标签并存  dx只有单标签
  // *****kf已经弃用单标签的配置，此组件主要是兼容从cc迁过来的单标签旧数据，单独文件入口，后续不会有功能更新，已被多级标签替代。
  import Vue from 'vue'
  import { getSingleOrMultiLabelNameById, getCache, deepClone } from '@/utils/m7Utils.js'
  import OperationLog from '@/components/public-modules/cust-tab-content/operation-log/'
  export default {
    name: 'SingleLabel',
    data () {
      return {
        checkOpearaDialog: false, // 操作日志的弹窗
        hasMulti: false, // 是否有多级标签的标志
        checkSingleLabel: false, // 单标签覆盖多级标签的弹窗
        interimId: '', // 打开确认窗口，临时存储的id
        interimName: '', // 打开确认窗口，临时存储的name
        cancleArr: [], // 弹框点击取消的时候，回退到单标签没有选中的状态
        checkCallLabel: this.checkLabels, // 解决标签覆盖之后，再change服务质量标签导致覆盖失败的问题
        operaHistory: [], // 操作日志的数据
        loading: true,
        preCheckLabel: [] // 数据处理后的所有标签，选中or不选中
      }
    },
    props: {
      callLabel: Array, // 所有的标签
      checkLabels: Array, // 当前选中的标签
      callSheetId: String, // 通话id
      disabled: Boolean, // 是否可点击
      flag: String, // 判断模块的标志 eg: QC
      phoneBarFlag: Boolean, // 是否是电话条
      refreshCallLabel: Number, // 点击质检评分的时候重新rest
      showOperaLog: {type: Boolean, default: false}, // 控制操作日志按钮是否显示
      isDialog: {type: Boolean, default: false} // 是否是弹窗类型的，弹窗类型的样式要做调整
    },
    computed: {
      isCalling () {
        return this.$store.state.cti.globalLet.isLabelShow
      }
    },
    methods: {
      getTabType () { // 获取tabType eg： cdr_my, cdr_all
        let routeArry = this.$route.path.split('/')
        let tabType = routeArry[3]
        return tabType || ''
      },
      getServerUrl () { // 获取当前坐席所在的pbx
        let pbxid = this.$store.state.session.user.pbx
        let curpbx = ''
        let assDomain = ''
        if (pbxid) {
          curpbx = getCache('accountPbx', pbxid)
          assDomain = curpbx.assAddr
        }
        return assDomain
      },
      groupCallLabel () { // 数据处理所有标签，选中or不选中
        let all = this.callLabel
        let check = []
        if (this.phoneBarFlag) {
          let labelIdObj = window.localStorage.getItem('labelIdObj')
          let newCallId = this.$store.state.cti.globalLet.currentCallSheetId
          if (newCallId) { // 前提要先先取到当前的通话id
            if (labelIdObj) {
              let localCallId = ''
              labelIdObj = JSON.parse(labelIdObj)
              localCallId = labelIdObj.callId
              if (newCallId !== localCallId) { // 当前id和本地存储的id不一致时，重新储存
                window.localStorage.setItem('labelIdObj', JSON.stringify({'callId': newCallId, 'labelIdArray': []}))
              } else {
                check = labelIdObj.labelIdArray
              }
            }
          }
        } else {
          check = this.checkCallLabel
        }
        let cancleArr = this.cancleArr
        let newCallLabel = []
        for (let item in all) {
          Vue.set(this.callLabel[item], 'checked', false) // checked之前
          for (let checkItem in check) {
            if (check[checkItem] === all[item]._id) {
              Vue.set(this.callLabel[item], 'checked', true)
              break
            }
          }
          for (let cancleItem in cancleArr) { // 为了弹框点击取消的时候，回退到单标签没有选中的状态
            if (cancleArr[cancleItem] === all[item]._id) {
              Vue.set(this.callLabel[item], 'checked', false)
              break
            }
          }
          newCallLabel.push(all[item])
        }
        this.hasMulti = false
        return newCallLabel
      },
      getAllCheck () { // 获取所有被选中的标签
        return this.preCheckLabel.filter(item => item.checked).map(item => item._id)
      },
      trunLableNameById (item) { // 通话标签id来匹配标签名字,取之前打过标签的名字
        if (!item) {
          return ''
        }
        let usedLabel = []
        if (item.indexOf('@') !== -1) { // 判断是不是多级
          this.hasMulti = true
          usedLabel = item.split('@') // @1@2@3拆分为数组
          usedLabel.pop()
        } else {
          this.hasMulti = false
        }
        let labelName = ''
        const allKeyLabels = this.$store.state.allKeyLabels || {}
        for (var j = 0; j < usedLabel.length; j++) {
          const nameStr = allKeyLabels !== {} ? allKeyLabels[usedLabel[j]] : ''
          if (nameStr) {
            labelName += nameStr + '>'
          }
        }
        labelName = labelName.substring(0, labelName.length - 1)
        return labelName
      },
      changeCallLabel (id, name, flag) {
        if (flag && this.hasMulti) { // 选中并且还有多级标签时
          this.checkSingleLabel = true // 打开确认窗口
          this.interimId = id // 把id和name临时存储起来
          this.interimName = name
          return
        }

        let nameArr = []
        let opArr = []
        let operation = ''
        if (flag === true) {
          operation = 'add'
        } else {
          operation = 'delete'
        }
        opArr.push(id)
        nameArr.push(name)
        if (this.isCalling && (this.callSheetId === this.$store.state.cti.globalLet.currentCallSheetId || this.phoneBarFlag)) { // 通话中 && (卡片中点开的是当前通话的id || 电话条)
          this.callingToRecod(operation, nameArr, id)
        } else {
          this.calledToRecord(operation, opArr, nameArr)
        }
      },
      callingToRecod (operation, nameArr, id) {
        let labelId = ''
        let labelIdArray = []
        let operateId = id + '##'
        let operateArr = []
        operateArr.push(operateId)
        let CheckIds = this.getAllCheck()
        for (let i = 0; i < CheckIds.length; i++) {
          labelId += CheckIds[i] + '##'
          labelIdArray.push(CheckIds[i])
        }
        let phoneData = this.$store.state.cti.globalLet.phone_data
        let phoneBarData = {
          Channel: phoneData._curChannel,
          pbx: phoneData.pbx_in_ip,
          operation: operation,
          label_op: operateArr,
          url: this.getServerUrl,
          callSheetId: this.$store.state.cti.globalLet.currentCallSheetId,
          value: 'LABELS' + labelId,
          name: nameArr
        }
        this.$store.dispatch('markCallSheetThroughCall', phoneBarData).then((resp) => {
          let labelIdObj = {
            callId: phoneBarData.callSheetId,
            labelIdArray: labelIdArray
          }
          this.commitLabelsUpdate(labelIdArray)
          window.localStorage.setItem('labelIdObj', JSON.stringify(labelIdObj))
        })
      },
      calledToRecord (operation, opArr, nameArr) {
        let data = {}
        data.operation = operation
        data.label_op = opArr
        data.name = nameArr
        data.label = this.getAllCheck()
        data.callSheetId = this.callSheetId
        let lastData = {data: data, type: this.getTabType}
        if (this.flag === 'QC') { // QC && UNDEAL 质检和通话待处理的打标签去掉处理坐席验证，即：处理坐席不是自己也可以打标签
          delete lastData.type
          lastData.data.flag = 'QC'
          this.$store.commit('singleLabelChange/qualityCheck')
        } else if (this.flag === 'UNDEAL') {
          lastData.data.flag = 'UNDEAL'
        }
        this.$store.dispatch('markCallSheet', lastData).then(resp => {
          if (resp) {
            this.commitLabelsUpdate(data.label)
          }
        })
      },
      commitLabelsUpdate (opArr) {
        this.$store.commit('call/COMMENTS', {id: this.callSheetId, labels: opArr, tabType: 'cdr_call'})
        this.$store.commit('call/COMMENTS', {id: this.callSheetId, labels: opArr, tabType: 'cdr_outbound'})
        this.$store.commit('call/COMMENTS', {id: this.callSheetId, labels: opArr, tabType: 'cdr_pending'})
        this.$store.commit('call/COMMENTS', {id: this.callSheetId, labels: opArr, tabType: 'cdr_all'})
      },
      warningCheckLabel () { // 确定单标签覆盖多级标签
        let data = {}
        let nameArr = []
        let opArr = []
        let operation = 'recover'
        opArr.push(this.interimId)
        nameArr.push(this.interimName)
        data.operation = operation
        data.label_op = opArr
        data.name = nameArr
        data.label = this.getAllCheck()
        data.callSheetId = this.callSheetId
        this.checkCallLabel = [] // 清空之前选中的多级标签
        this.checkCallLabel.push(this.interimId)
        this.cancleArr = [] // 清空点击取消之后存进去的cancleArr
        this.hasMulti = false
        let lastData = {data: data, type: this.getTabType}
        if (this.flag === 'QC') { // QC && UNDEAL 质检和通话待处理的打标签去掉处理坐席验证，即：处理坐席不是自己也可以打标签
          delete lastData.type
          lastData.data.flag = 'QC'
          this.$store.commit('singleLabelChange/qualityCheck')
        } else if (this.flag === 'UNDEAL') {
          lastData.data.flag = 'UNDEAL'
        }
        this.$store.dispatch('markCallSheet', lastData).then((resp) => {
          if (resp) {
            this.checkSingleLabel = false // 关闭窗口
          }
        })
      },
      cancleWarning () { // 取消单标签覆盖多级标签
        this.checkSingleLabel = false
        let id = this.interimId
        this.cancleArr.push(id)
        this.preCheckLabel = deepClone(this.groupCallLabel()) // 取消覆盖标签时要重新把选中状态还原回去
      },
      checkOperationLog () {  // 查询通话标签的操作日志
        let lastData = {data: {callSheetId: this.callSheetId}, type: this.getTabType}
        this.$store.dispatch('getCallLabelOPHistory', lastData).then((resp) => {
          if (resp.success) {
            let list = resp.history.reverse()
            this.operaHistory = list
            this.checkOpearaDialog = true
          } else {
            this.$message.error(this.$t('call.getOperateFail'))
          }
        })
      }
    },
    components: {
      OperationLog
    },
    watch: {
      refreshCallLabel () { // 点开窗口的时候，重新加载
        this.checkCallLabel = this.checkLabels
        console.log(this.checkLabels, 'watch=======')
        this.preCheckLabel = deepClone(this.groupCallLabel())
      }
    },
    mounted () {
      setTimeout(() => { // 为了解决第一次加载这个组件时，props没有把最新数据传下来的问题
        this.checkCallLabel = this.checkLabels
        console.log(this.checkLabels, 'mounted=======')
        this.preCheckLabel = deepClone(this.groupCallLabel()) // deepClone当卡片中的标签组件和详情中的同时出现时，会数据互相污染
        this.loading = false
      }, 1000)
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .clear-wrap
    padding-top 16px
    &:after
      display block
      content ''
      clear both
  .label-box
    position relative
    float left
    margin 0 20px 10px 0
    input
      sing-inp()
    input:checked+span
      sing-sped()
    input+span
      sing-sp()
    input:checked+span
      &:after
        sing-af()
      &:before
        sing-be()
  input[disabled]
    cursor not-allowed
  .label-clear
    float left
    &:after
      display block
      content ''
      clear both
  .ul-name
    li
      border 1px solid $c-border2
      min-width 6em
      height 26px
      box-sizing border-box
      line-height 26px
      max-width 35em
      display block
      border-radius 3px
      text-align center
      position relative
      float left
      padding 0 10px
      margin 0px 20px 16px 0
      overflow hidden
      text-overflow ellipsis
      white-space nowrap
  .single-label-grade
    li
      max-width 20em
  .clearfix:after
    display block
  .has-multi
    border-top 1px solid #efeef3
    padding-top 16px
  .zhezhao
    display none
    position fixed
    top 0
    left 0
    right 0
    bottom 0
    background $cf-gray0
    opacity .5
    z-index 6
  .hide-zhezhao
    display none
  .show-zhezhao
    display block
  .label-title
    width 6em
    position absolute
    top 0
    left 0
  .QC-label-select
    .label-title
      width 100px
    .label-contain
      margin-left 100px
  .box-wrap
    position relative
  .label-contain
    margin-left 6em
  .phoneBar-padding
    margin-left 0
  .label-cursor
    cursor pointer
</style>
